package com.coder.bike.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coder.bike.entity.BikeInfo;
import com.coder.bike.entity.Order;
import com.coder.bike.mapper.BikeInfoMapper;
import com.coder.bike.mapper.OrderMapper;
import com.coder.bike.service.IOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private BikeInfoMapper bikeInfoMapper;


    @Override
    public Page<Order> search(Page<Order> page, Order order) {
        return baseMapper.search(page, order);
    }

    @Override
    public Page<Order> searchUnfinished(Page<Order> page, Order order) {
        return baseMapper.searchUnfinished(page, order);
    }

    @Override
    public boolean returnBike(Order order) {
        try {
            String bikeId = order.getBikeNum();
            BikeInfo bikeInfo = bikeInfoMapper.selectByBikeId(bikeId);
            // 更新订单信息
            order.setEndTime(LocalDateTime.now());
            order.setStatus(true);
            if (bikeInfo.getTypeId() == 2) {
                bikeInfo.setBattery(order.getEndBattery());
            }
            bikeInfo.setStatus((byte) 0); // 0表示可用
            bikeInfo.setMileage(bikeInfo.getMileage()+order.getEndMileage()); // 更新里程
            bikeInfoMapper.updateById(bikeInfo);


            return this.updateById(order);
        } catch (Exception e) {
            throw new RuntimeException("单车归还失败", e);
        }
    }

    @Override
    public long countViolation(String bikeNum) {
        return baseMapper.countViolation(bikeNum);
    }

    @Override
    public boolean returnDeposit(Integer orderId) {
        Order order = this.getById(orderId);
        if (order != null) {
            order.setDepositStatus(true);
            return this.updateById(order);
        }
        return false;
    }

    @Override
    public boolean save(Order order) {
        String bikeId = order.getBikeNum();
        BikeInfo bikeInfo = bikeInfoMapper.selectByBikeId(bikeId);
        if (bikeInfo.getTypeId() == 2) {
            order.setStartBattery(bikeInfo.getBattery());
        }
        String number = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());
        order.setOrderNum(number);
        order.setStartTime(LocalDateTime.now());
        order.setStartMileage(0);
        return baseMapper.insert(order) == 1;
    }
}